package com.sparrow.source.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sparrow.source.common.dto.CurrReportRequest;
import com.sparrow.source.common.dto.ReportTable;
import com.sparrow.source.common.dto.ReportTableRequest;
import com.sparrow.source.common.dto.Result;
import com.sparrow.source.common.enums.ChannelEnums;
import com.sparrow.source.common.enums.MatchEnums;
import com.sparrow.source.common.enums.ResultEnum;
import com.sparrow.source.service.IIasVerifyReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author bryceyung
 * @since 2024/12/9
 */
@RequestMapping("/v1/report")
@Controller
@Slf4j
public class ReportController {

    @Autowired
    private IIasVerifyReportService verifyReportService;

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 考勤统计表格
     *
     * @param request
     * @param page
     * @return
     */
    @PostMapping("queryReportTable")
    @ResponseBody
    public Result queryReportTable(@RequestBody ReportTableRequest request, Page<ReportTable> page) {
        return Result.build(ResultEnum.SUCCESS).setObject(verifyReportService.queryReportTable(request, page));
    }

    @GetMapping("export")
    @ResponseBody
    public void exportReportTable(HttpServletResponse response) {
        try {
            ReportTableRequest reportTableRequest = new ReportTableRequest();
            Page<ReportTable> page = new Page<>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            IPage<ReportTable> pageRes = verifyReportService.queryReportTable(reportTableRequest, page);
            List<ReportTable> reportList = pageRes.getRecords();
            AtomicReference<Integer> index = new AtomicReference<>(1);
            reportList.forEach(data -> {
                data.setIndex(index.get());
                data.setChannel(ChannelEnums.getByChannel(data.getChannel()).getChannelName());
                if (data.getCheckType() != null) {
                    data.setCheckTypeName(data.getCheckType() == 1 ? "签到" : "签退");
                }
                if (data.getMatchRes() != null) {
                    data.setMatchResName(MatchEnums.getByVal(data.getMatchRes()).getDesc());
                }
                index.getAndSet(index.get() + 1);
            });
            // 设置响应
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("考勤统计", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + sdf.format(new Date()) + ".xlsx");

            // 写入数据
            EasyExcel.write(response.getOutputStream(), ReportTable.class).sheet("sheet1").doWrite(reportList);
        } catch (Exception e) {
            log.error("[exportReportTable] error", e.getMessage(), e);
        }
    }

    @PostMapping("barChar1")
    @ResponseBody
    public Result queryBarChart1() {
        return Result.build(ResultEnum.SUCCESS).setObject(verifyReportService.queryDeviceChannel());
    }

    @PostMapping("queryDeviceCheckCountWeekly")
    @ResponseBody
    public Result queryDeviceCheckCountWeekly() {
        return Result.build(ResultEnum.SUCCESS).setObject(verifyReportService.queryCheckCountWeekly());
    }

    @PostMapping("getDesktopReport")
    @ResponseBody
    public Result getDesktopReport() {
        return Result.build(ResultEnum.SUCCESS).setObject(verifyReportService.getDesktopReport());
    }

    @PostMapping("queryCurrReport")
    @ResponseBody
    public Result queryCurrReport(@RequestBody CurrReportRequest reportRequest){
        return Result.build(ResultEnum.SUCCESS).setObject(verifyReportService.queryCurrDate(reportRequest.getStartDate(),reportRequest.getEndDate(),reportRequest.getDeviceId()));
    }
}
